<template>
  <div class="area">
    <div class="about">
      <h1 class="head">{{title}}</h1>
      <div>
        <div class="content" v-for="(item,index) in content" :key="index">
          <p>{{item}}</p>
        </div>
      </div>
    </div>
    <div class="message">
      <div>
        <h1 class="head">留下联系方式&nbsp;&nbsp;我们将联系您</h1>
        <!-- <h2 class="second">欢迎您拨打服务热线12345678910</h2> -->
      </div>
      <el-form :model="ruleForm" size="small" :rules="rules" ref="ruleForm" label-width="100px"
        class="demo-ruleForm form">
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="公司名：" prop="company">
          <el-input v-model="ruleForm.company"></el-input>
        </el-form-item>
        <el-form-item label="手机：" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <!-- <el-form-item label="邮箱：" prop="mail">
          <el-input v-model="ruleForm.mail"></el-input>
        </el-form-item> -->
        <el-form-item label="留言：" prop="message">
          <el-input v-model="ruleForm.message"></el-input>
        </el-form-item>
        <el-form-item label="验证码：" prop="usercode">
          <el-input v-model="ruleForm.usercode"></el-input>
        </el-form-item>
        <div style="text-align: center;">
          <canvas id="canvas" width="100px" height="50px" @click="changecode"></canvas>
        </div>

        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'HomeAbout',
  data () {
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8|9][0-9]{9}$/
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback()
        } else {
          callback(new Error('请输入正确的邮箱格式'))
        }
      }, 100)
    }
    return {
      code: '',
      ruleForm: {
        name: '',
        company: '',
        phone: '',
        message: '',
        usercode: ''
      },
      content: [],
      title: '',
      rules: {
        name: [
          { required: true, message: '请输入您的姓名', trigger: 'blur' },
          { min: 2, max: 4, message: '长度在 2 到 4 个字符', trigger: 'blur' }
        ],
        company: [
          { required: true, message: '请输入您的姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        phone: [
          { validator: checkPhone, trigger: 'blur' },
          { required: true }
        ],
        mail: [
          { validator: checkEmail, trigger: 'blur' },
          { required: true }
        ],
        message: [
          { required: true, message: '请输入您的留言', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        usercode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 4, max: 4, message: '请输入正确的验证码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.usercode === this.code) {
            var formData = new FormData()
            formData.append('company', this.ruleForm.company)
            formData.append('content', this.ruleForm.message)
            // formData.append('email', this.ruleForm.mail)
            formData.append('name', this.ruleForm.name)
            formData.append('telephone', this.ruleForm.phone)
            formData.append('updateTime', this.getTime())
            this.$axios({
              method: 'post',
              url: '/words/insert',
              data: formData
            }).then((res) => {
              if (res.data.message === 'SUCCESS') {
                this.success()
                this.resetForm('ruleForm')
              } else {
                this.failed('请选择电话咨询。')
              }
            })
          } else {
            this.failed('验证码错误！')
          }
        }
      })
    },
    getTime () {
      var date = new Date()
      var seperator1 = '-'
      var seperator2 = ':'
      var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var strDate = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
        ' ' + date.getHours() + seperator2 + date.getMinutes() +
        seperator2 + date.getSeconds()
      return currentdate
    },
    success () {
      this.$notify({
        title: '成功',
        message: '留言成功。',
        type: 'success'
      })
    },
    failed (text) {
      this.$notify.error({
        title: '失败',
        message: text
      })
    },
    notice () {
      this.$alert('验证码错误', '提醒', {
        confirmButtonText: '确定',
        callback: action => {
          this.$message({
            type: 'info',
            message: `action: ${action}`
          })
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    getRanNum () {
      var result = []
      var code = ''
      for (var i = 0; i < 4; i++) {
        var ranNum = Math.ceil(Math.random() * 9) // 生成一个0到25的数字
        // 大写字母'A'的ASCII是65,A~Z的ASCII码就是65 + 0~25;然后调用String.fromCharCode()传入ASCII值返回相应的字符并push进数组里
        // result.push(String.fromCharCode(65 + ranNum))
        code = code + ranNum
        result.push(ranNum)
      }
      this.code = code
      this.useCode()
    },
    useCode () {
      var canvas = document.getElementById('canvas')
      if (canvas.getContext) {
        var ctx = canvas.getContext('2d')
        ctx.font = 'bold italic 20px arial'
        ctx.fillText(this.code, 30, 33)
      }
    },
    changecode () {
      var canvas = document.getElementById('canvas')
      if (canvas.getContext) {
        var ctx = canvas.getContext('2d')
        ctx.clearRect(0, 0, 100, 50)
      }
      this.getRanNum()
    },
    getData () {
      this.$axios({
        method: 'get',
        url: '/introduction/get'
      }).then((res) => {
        this.title = res.data.data.title
        this.content = res.data.data.content.split('<span>')
      })
    }
  },
  mounted () {
    this.getRanNum()
    this.getData()
  }
}
</script>

<style scoped>
.area {
  overflow: hidden;
  display: flex;
  justify-content: space-around;
}
.about {
  width: 50%;
  height: 600px;
  background: #364a62;
  text-align: center;
  color: #ffffff;
  padding-top: 50px;
}
.message {
  width: 50%;
  height: 600px;
  background: #ffffff;
  text-align: center;
  padding-top: 50px;
}
.head {
  font-weight: 800;
  font-size: 30px;
  padding: 50px 0 0 0;
}
.content {
  font-size: 18px;
  padding: 20px 20px 0 20px;
  line-height: 30px;
  text-align: center;
  text-indent: 2rem;
}
.second {
  font-size: 18px;
  padding-top: 20px;
}
.form {
  padding: 20px 100px;
}
canvas {
  box-shadow: 0 0 10px 0 #eeeeee;
  margin: 5px 0 15px 0;
}
</style>
